<?php
/**
* Avatar/Gravatar - show avatar next to the header and comments of article
* @package avatar_gravatar
* @author Tomasz Dobrzyński
* @version 1.12.1
* @copyright (C) 2008 by Tomasz Dobrzyński
* @license GNU General Public License version 2 http://www.gnu.org/licenses/old-licenses/gpl-2.0.html#SEC4
**/

defined( '_JEXEC' ) or die( 'Direct Access to this location is not allowed.' );

jimport( 'joomla.event.plugin' );

class plgSystemAvatar_Gravatar extends JPlugin
{
	function plgSystemAvatar_Gravatar(&$subject)
	{
		parent::__construct($subject);
	
		$this->_plugin = JPluginHelper::getPlugin( 'system', 'avatar_gravatar' );
		$this->_params = new JParameter( $this->_plugin->params );

		global $mainframe;

		//enable CSS plugin template
		$css_control = $this->_params->get( 'css_control', 'plugin' );
		if( $css_control=='plugin' )
		{
			$site_content = &JFactory::getDocument();
 			$site_content->addStyleSheet( JURI::base().'plugins/system/avatar_gravatar/image.css', 'text/css' );
		}
	}

	function _avatar_path(&$author, $guest)
	{
		$param_default_image = $this->_params->get( 'default_image' , 'default.avatar@gmail.com');

		/* checking whether author of article is guest or not */
		$author_mail = '';
		$article_guest = 0;
		if( $guest!='not' )
		{
			$metadata_registry = new JRegistry();
			$metadata_registry->loadINI($guest);
			$author_mail = $metadata_registry->getValue('created_by_email');

			//if e-mail filled in by guest is empty, read from plugin default avatar/gravatar
			if( $author_mail=='' )
				$author_mail = $param_default_image;
			else
				$article_guest = 1;

			$author_mail = urldecode(html_entity_decode($author_mail));
		}

		//checking whether $param_default_image is avatar or gravatar
		if(strstr($param_default_image, '@') == true)
			$default_gravatar = 1;
		else
			$default_gravatar = 0;


		$db = &JFactory::getDBO();
		//get author's avatar
		$query = 'SELECT params FROM `#__users` WHERE name="'.$author.'"';
		$db->setQuery( $query );
		$parametry = $db->loadObjectList();


		if( $article_guest==0 )
		{
			$name = null;

			//get author's avatar name form his config
			if( count($parametry)>0 )
				$table = explode("\n", $parametry[0]->params);
			else
				$table = NULL;

			/* checking that in selected row is variable 'avatar'
			   count-3 because has exploded by new line ('\n') */
			for($m=0; $m<=count($table)-3; $m++)
			{
				$rozlozony = explode('=', $table[$m]);
				if( $rozlozony[0]=='avatar' )
				{
					$name = $rozlozony[1];
	
					//ending loop
					$m = count($table)-3;
				}
			}

			//if user doesn't set own avatar in UserMeta config
			if( strlen($name)==null )
				$name = $param_default_image;
	
			/* accepting not full path; when beginning from slash */
			if( $name{0}=='/' )
			{
				/* delete slash form beginning of the string
				BEFORE: http://server.org/joomla//images/banners/shop-ad.jpg
				AFTER:  http://server.org/joomla/images/banners/shop-ad.jpg
				now main 'dir' for plugin is Joomla!, not server */
				$path_element='';
				for($u=1; $u<=strlen($name)-1; $u++)
				{ $path_element.=$name{$u}; }
	
				$name = JURI::root().$path_element;
			}
	
			//checking that variable is gravatar or http avatar
			if(strstr($name, '@') == true)
				$name_gravatar = 1;
			else
				$name_gravatar = 0;

			//return author's 'avatar's URL' or 'gravatar's username'
			if( $name_gravatar==1 )
				return 'http://www.gravatar.com/avatar.php?gravatar_id='.md5($name);
			else
				return $name;
		}
		else
		{
			if( $default_gravatar==1 )
				return 'http://www.gravatar.com/avatar.php?gravatar_id='.md5($author_mail).'&default='.urlencode('http://www.gravatar.com/avatar.php?gravatar_id='.md5($param_default_image));
			else
				return 'http://www.gravatar.com/avatar.php?gravatar_id='.md5($author_mail).'&default='.$param_default_image;
		}
	}

	function _create_max_size(&$param_img_width, &$param_img_height, &$real_width, &$real_height)
	{
		//calculation quotient of image size
		$k = ($real_width*1.00) / 80;

		$param_img_width = $real_width / $k;
		$param_img_height = $real_height / $k;
	}

	function _draw_avatar(&$row, &$author, $comment)
	{
		$CONENT = null;

		$guest_username = NULL;
		$guestID = NULL;

		//reading guest ID
		$yvcomment = JPluginHelper::getPlugin( 'content', 'yvcomment' );
		if( count($yvcomment)>0 )
		{
			jimport('joomla.user.helper');
			$yvcomment_params = new JParameter( $yvcomment->params );
			$guest_username = $yvcomment_params->get('guest_username', null);
			$guestID = JUserHelper::getUserId($guest_username);
		}

		/* reading path of image of gravatar username (automaticly detected)
		  two params: for guest, and logged-in user; to minimize delivery of
		  params and warnings or notices in all_errors, PHP */
		if( isset($row->metadata)==1 )
		{
			if( $row->created_by==$guestID )
				$url = $this->_avatar_path($author, $row->metadata);
			else
				$url = $this->_avatar_path($author, 'not');
		}
		else
		{
			$url = $this->_avatar_path($author, 'not');
			/*
			$metadata_registry = new JRegistry();
			$metadata_registry->loadINI($row->metadata);
			$author_mail = $metadata_registry->getValue('created_by_email');
			echo $author_mail;
			*/
		}

		/* reading real size of image, but ohhh, hmmm...
		   only when URL outgoing connection are allowed
		   ---------------------------------------------
		   image of size is also 0x0px, when image doesn't exist
		   so it is hard to indicate what type return getimagesize */
		if( (ini_get('allow_url_fopen') != null) || (ini_get('allow_url_fopen') == '1') || ( strtolower(ini_get('allow_url_fopen')) == 'true') )
		{
			list( $real_width, $real_height ) = @getimagesize($url);
			if( ($real_width==0) || ($real_height==0) || ($real_width==null) || ($real_height==null) )
				$url = 'http://www.gravatar.com/avatar.php?gravatar_id='.md5('default.avatar@gmail.com');
		}
		else
		{
			$real_width = 0;
			$real_height = 0;
		}

		//reading params
		$param_is_set_size = $this->_params->get( 'is_set_size', '1' );
		$param_img_width = $this->_params->get( 'img_width', '55' );
		$param_img_height = $this->_params->get( 'img_height', '55' );
		$param_img_percent = $this->_params->get( 'img_percent', '50' );
		$advanced_template = $this->_params->get( 'advanced_template', '0' );

		//checking whether datas have correct type and good value of size
		if( !is_numeric($param_img_width) )
			$param_img_width = 55;
		if( $param_img_width > 80 )
			$param_img_width = 80;

		if( !is_numeric($param_img_height) )
			$param_img_height = 55;
		if( $param_img_height > 80 )
			$param_img_height = 80;

		/* security is most important
		   if image is bigger than 80px width,
		   image must be resized */
		if( $param_is_set_size==0 && $real_width > 80 )
			$this->create_max_size($param_img_width, $param_img_height, $real_width, $real_height);
		
		/* changing size of image according to the state of config
		   oh, even now I have problems with reading this values ;) */
		if( $comment==1 && $param_is_set_size==0 && (($real_width>0) || ($real_height>0)) )
		{
			if( $real_width <= 80 )
			{
				$param_img_width = $real_width * $param_img_percent / 100;
				$param_img_height = $real_height * $param_img_percent / 100;
			}
			else
			{
				$param_img_width = $param_img_width * $param_img_percent / 100;
				$param_img_height = $param_img_height * $param_img_percent / 100;
			}
		}
		elseif( $comment==1 && $param_is_set_size==1 )
		{
			$param_img_width = $param_img_width * $param_img_percent / 100;
			$param_img_height = $param_img_height * $param_img_percent / 100;
		}

		$CONTENT='';
		// $CONTENT variable is very important, this var will be print on screen
		if( $comment==1 )
			$CONTENT = '<img src="'.$url;
		else
		{
			if( JRequest::getVar('view')=='frontpage' )
			{
				if( $advanced_template==0 )
					$CONTENT='<table style="width:100%; float:right;" cols=1><tr width="100%"><td colspan=2 >';
				$CONTENT .= '<img src="'.$url;
			}
			else
			{
				if( $advanced_template==0 )
					$CONTENT = '<table style="width:100%;"><tr><td><img src="'.$url;
			}
		}

		//changing size for gravatar [depend on plugin configuration]
		if( $comment==1 )
		{
			if( strlen(strpos($url, "//www.gravatar.com"))>0 )
			{
				if( strlen(strpos($url, "default"))>0 )
					$CONTENT .= '" width='.$param_img_width.' height='.$param_img_height;
				else
					$CONTENT .= '&size='.$param_img_width.'"';
			}
			else
				$CONTENT .= '" width='.$param_img_width.' height='.$param_img_height;
		}
		elseif( $comment==0 )
		{
			if( ($param_is_set_size==1) && (strlen(strpos($url, "//www.gravatar.com"))>0) )
			{
				if( strlen(strpos($url, "default"))>0 )
					$CONTENT .= '" width='.$param_img_width.' height='.$param_img_height;
				else
					$CONTENT .= '&size='.$param_img_width.'"';
			}
			elseif( $param_is_set_size==1 )
				$CONTENT .= '" width='.$param_img_width.' height='.$param_img_height;
			elseif( $param_is_set_size==0 )
			{
				/* this is special exception because there
				   is no params of image in CONTENT */
				if( $real_width > 80 )
					$CONTENT .= '" width='.$param_img_width.' height='.$param_img_height;
				else
					$CONTENT.= '"';
			}
		}

		$CONTENT .= ' title="'.$row->created_by_alias;

		//if selected CSS styling, enabling styles to img tag
		$css_control = $this->_params->get( 'css_control', 'plugin' );
		if( $comment==1 )
		{
			if( ($css_control=='plugin') || ($css_control=='template') )
				$CONTENT .= '" class="avatar_gravatar-comment" />';
		}
		else
		{
			if( ($css_control=='plugin') || ($css_control=='template') )
				$CONTENT .= '" class="avatar_gravatar-header" />';

			//closing opened somewhere below tags (not advanced templates)
			if( $advanced_template==0 )
				$row->text = '</td></tr></table>'.$row->text.'';
		}

		//writing on screen
		return $CONTENT;
	}

	function onAfterDisplayContent($row)
	{
		/*it's here because have been used both method:
		  float:left & right. When it happen, empty line
		  dissapears :/ ??? No, no, no... it's too strange
		  for teenager ;) Just leave this event alone */
		$user = &JFactory::getUser();
		if( ($user->guest==0) && ($user->getParam( 'user_is_set_header_avatar', '1' )==1) )
		{
			if( JRequest::getVar('view')=='frontpage' )
				return '<br>&nbsp;';
		}
	}

	function onPrepareContent(&$row, &$params)
	{
		global $mainframe;
		global $option;

		/* Main source of Avatar/Gravatar plugin
		   everything depend on this function */
		$user = &JFactory::getUser();

		//reading SYSTEM config
		$system_is_set_header_avatar = $this->_params->get( 'system_is_set_header_avatar', '1' );
		$system_is_set_comment_avatar = $this->_params->get( 'system_is_set_comment_avatar', '1' );

		$advanced_template = $this->_params->get( 'advanced_template', '0' );
		
		//reading USER config from UserMeta System Plugin
		if( $user->guest==0 )
		{
			$user_is_set_header_avatar = $user->getParam( 'user_is_set_header_avatar', '1' );
			$user_is_set_comment_avatar = $user->getParam( 'user_is_set_comment_avatar', '1' );
		}

		//avatar inside header of article
		if( $option=='com_content' )
		{
			if( JRequest::getVar('format')!='pdf' )
			{
				if( ($user->guest==1) && ($system_is_set_header_avatar==1) )
				{
					if( $advanced_template==1 )
						$row->avatar = $this->_draw_avatar($row, $row->author, 0);
					else
						print $this->_draw_avatar($row, $row->author, 0);
				}
				elseif( ($user->guest==0) && ($user_is_set_header_avatar==1) )
				{
					if( $advanced_template==1 )
						$row->avatar = $this->_draw_avatar($row, $row->author, 0);
					else
						print $this->_draw_avatar($row, $row->author, 0);
				}
			}
		}
		elseif( $option=='com_yvcomment' ) //avatar inside comment section
		{
			if( $mainframe->isAdmin() )
				$row->avatar = $this->_draw_avatar($row, $row->AuthorName, 1);
			elseif( ($user->guest==1) && ($system_is_set_comment_avatar==1) )
				$row->avatar = $this->_draw_avatar($row, $row->AuthorName, 1);
			elseif( ($user->guest==0) && ($user_is_set_comment_avatar==1) )
				$row->avatar = $this->_draw_avatar($row, $row->AuthorName, 1);
		}
	}
}
?>
